import requests
import fake_useragent
import json
import time
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active
ws.title = '中国土地市场网全国的土地交易数据'
ws.append(('编号','行政区', '土地坐落', '总面积(㎡)','土地用途','供应方式','签订日期','成交价格'))

url = 'https://api.landchina.com/tGdxm/result/list'
request_data = {
    "pageNum": 1,
    "pageSize": 10,
    "startDate": "",
    "endDate": ""}
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0',
    'Content-Type': 'application/json'
}
res = requests.post(url,json.dumps(request_data),headers=headers).text

# 解析数据封装成对象
res = json.loads(res)['笔记.md']['list']
res_list = list(res)
# print(res_list)
count = 0
for row in res_list:
    # print(row)
    gdGuid = row['gdGuid'] #编号
    xzqDm = row['xzqDm'] # 行政区
    tdZl = row['tdZl'] # 土地坐落
    gyFs = row['gyFs'] # 总面积(㎡)
    gyMj = row['gyMj'] # 土地用途
    tdYt = row['tdYt'] # 供应方式
    qdRq = row['qdRq'] # 签订日期
    xzqFullName = row['xzqFullName']
    # print(gdGuid)
    url2 = 'https://api.landchina.com/tGdxm/result/detail'
    res2 = requests.post(url2,json.dumps({'gdGuid':gdGuid}),headers=headers).text
    # print(gdGuid)
    cjJg = json.loads(res2)['relate'][0]['cjJg']
    # print(gdGuid,xzqDm,tdZl,gyMj,tdYt,qdRq,xzqFullName,cjJg)
    # hbjds1e5976dc-504d-4e20-ad24-849b85a662a6 623022 卓尼县扎古录镇柏林村 1.282 公用设施用地 2023-07-17T12:07:00 甘肃省甘南藏族自治州卓尼县 0
    ws.append((gdGuid,xzqFullName,tdZl,gyMj,tdYt,qdRq,qdRq,cjJg))
    count += 1
    print(count)
    time.sleep(5)
    # break
    # print(cjJg)
    # 写数据进excel表格

wb.save('中国土地市场网全国的土地交易数据.xlsx')
